package org.moon.framework.autoconfigure.sms.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.sms.SmsService;
import org.moon.framework.autoconfigure.sms.domain.SmsResponse;
import org.moon.framework.autoconfigure.sms.props.SmsProperties;
import org.moon.framework.autoconfigure.utils.Func;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 腾讯云短信发送类
 * @author ninglong
 */
@Slf4j
public class TencentSmsProviderImpl implements SmsService,SmsProvider {

    private static final String NATION_CODE = "86";

    private SmsMultiSender smsSender = null;
    private SmsProperties smsProperties = null;

    @Override
    public SmsService builder(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
        smsSender = new SmsMultiSender(Func.toInt(smsProperties.getAccessKey()), smsProperties.getSecretKey());
        return this;
    }

    @Override
    public SmsResponse sendSingleSms(String mobile, String templateCode, Map<String, String> templateParams) {
        List<String> mobiles = Lists.newArrayList();
        mobiles.add(mobile);
        return sendMultiSms( mobiles, templateCode, templateParams);
    }

    @Override
    public SmsResponse sendMultiSms(List<String> mobiles, String templateCode, Map<String, String> templateParams) {
        try {
            String[] params = Func.toStrArray(String.join(Func.COMMA, templateParams.values()));
            SmsMultiSenderResult senderResult = smsSender.sendWithParam(
                    NATION_CODE,
                    Func.toStrArray(String.join(Func.COMMA, mobiles)),
                    Func.toInt(templateCode),
                    params,
                    smsProperties.getSignName(),
                    StringPool.EMPTY, StringPool.EMPTY
            );
            return new SmsResponse(senderResult.result == 0, senderResult.result, senderResult.toString());
        } catch (HTTPException | IOException e) {
            log.error(e.getMessage(), e);
            return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
    }
}
